package com.xn.app.muying.util;

import android.content.Context;
import android.media.MediaPlayer;
import android.media.TimedText;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.util.Log;

import com.xn.app.muying.activity.VoiceSolutionActivity;
import com.xn.app.muying.activity.VoiceSolutionDetailActivity;
import com.xn.app.muying.activity.VoiceSolutionListActivity;
import com.xn.app.muying.fragment.HomeFragment;

import java.io.IOException;

/**
 * 音乐播放器
 * Created by gaoge on 2017/8/10.
 */

public class MyMediaPlayer {

    //播放器
    public static MediaPlayer mediaPlayer = null;
    //记录播放的id
    private static int idPlayer = -1;

    /**
     * 创建网络mp3
     *
     * @return
     */
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    public MediaPlayer createNetMp3(String mp3Url, int id) {
        String url = mp3Url;
        //如果第一次启动，会自动记录播放的id
        if (idPlayer == -1) {
            idPlayer = id;
        }

        //如果mediaPlayer不为空的话，就判断是否是同一个语音
        if (mediaPlayer != null) {
            if (idPlayer == id) {
                return mediaPlayer;
            } else {
                stopNetMp3();
                idPlayer=id;
            }

        }
        try {
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setDataSource(url);
            mediaPlayer.prepare();
            //当播放完音频资源时，会触发onCompletion事件，可以在该事件中释放音频资源，
            //以便其他应用程序可以使用该资源:
            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    stopNetMp3();
                    VoiceSolutionDetailActivity.mediaPlayer = null;
                }
            });
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
            return null;
        } catch (IllegalStateException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        return mediaPlayer;
    }

    /**
     * 开始播放
     */
    public void startNetMp3() {
        if (mediaPlayer != null) {
            try {
                mediaPlayer.start();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 暂停播放
     */
    public void pauseNetMp3() {
        if (mediaPlayer != null) {
            mediaPlayer.pause();//暂停
        }
    }

    /**
     * 停止播放
     */
    public void stopNetMp3() {
        if (mediaPlayer != null) {
            try {
            idPlayer = -1;
            mediaPlayer.stop();//停止播放
            mediaPlayer.reset();
            mediaPlayer.release();//释放资源
            mediaPlayer = null;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}
